import { Geometry } from "./geometry/geometry";

export class Map {
  _canvas: HTMLCanvasElement;
  _ctx: CanvasRenderingContext2D;
  _geometries: Geometry[] = [];
  //用于记录拖拽起始位置
  _drag: any = {
    flag: false,
    start: {
      x: 0,
      y: 0,
    },
    end: {
      x: 0,
      y: 0,
    },
  };

  constructor(id: string) {
    this._canvas = document.getElementById(id) as HTMLCanvasElement;
    this._ctx = this._canvas.getContext("2d");
    //注册双击监听
    this._canvas.addEventListener("dblclick", this._onDoubleClick.bind(this));
    this._canvas.addEventListener("mousedown", this._onMouseDown.bind(this));
    this._canvas.addEventListener("mousemove", this._onMouseMove.bind(this));
    this._canvas.addEventListener("mouseup", this._onMouseUp.bind(this));
  }

  //临时，后期考虑Layer进行管理
  addGeometry(geometry: Geometry) {
    geometry.draw(this._ctx);
    this._geometries.push(geometry);
  }

  //重绘
  redraw() {
    this._ctx.save();
    this._ctx.setTransform(1, 0, 0, 1, 0, 0);
    this._ctx.clearRect(0, 0, this._canvas.width, this._canvas.height);
    this._ctx.restore();
    this._geometries.forEach((geometry) => geometry.draw(this._ctx));
  }

  //双击2倍放大
  _onDoubleClick(event) {
    this._ctx.scale(2, 2);
    this.redraw();
  }

  _onMouseDown(event) {
    this._drag.flag = true;
    this._drag.start.x = event.x;
    this._drag.start.y = event.y;
  }

  _onMouseMove(event) {}

  _onMouseUp(event) {
    if (this._drag.flag) {
      this._drag.end.x = event.x;
      this._drag.end.y = event.y;
      //矩阵噩梦从此开始
      const matrix = (this._ctx as any).getTransform();
      this._ctx.translate(
        (this._drag.end.x - this._drag.start.x) / matrix.a,
        (this._drag.end.y - this._drag.start.y) / matrix.d
      );
      this.redraw();
    }
    this._drag.flag = false;
  }

  destroy() {
    //取消双击监听
    this._canvas.removeEventListener("dblclick", this._onDoubleClick);
    this._canvas.removeEventListener("mousedown", this._onMouseDown);
    this._canvas.removeEventListener("mousemove", this._onMouseMove);
    this._canvas.removeEventListener("mouseup", this._onMouseUp);
  }
}
